package com.ktjy.task;


import com.ktjy.websocket.WebSocketServer;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
public class WebSocketTask {
    static Map<String, Session> map = new HashMap<>();
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 通过WebSocket每隔5秒向客户端发送消息
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void sendMessageToClient() {
        webSocketServer.sendToAllClient("这是来自服务端的消息：" + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
    }


    /**
     * 向所有连接的会话发送消息的方法
     *
     * @param message 要发送的消息内容
     * @throws IOException 当发送消息过程中发生I/O错误时抛出
     */
    public void send(String message) throws IOException {
        // 获取所有会话的集合
        Collection<Session> values = map.values();
        // 遍历所有会话
        for (Session session : values) {
            // 向每个会话发送文本消息
            session.getBasicRemote().sendText(message);
        }
    }
}
